import React, { useState, useCallback } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Upload,
  message,
  Tag,
  Tooltip,
  Tabs,
  Badge,
  Popconfirm,
  Typography,
  InputNumber,
  Progress,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  DownloadOutlined,
  UserOutlined,
  TeamOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import type { UploadProps } from "antd";
import type { TabsProps } from "antd";
import styled from "styled-components";

const { Option } = Select;
const { Text } = Typography;

// 类型定义
interface Student {
  id: string;
  name: string;
  studentId: string;
  gender: "男" | "女";
  phone: string;
  email: string;
  group?: string;
  performance?: "excellent" | "good" | "normal" | "poor";
  attendance?: number;
  scores?: {
    midterm?: number;
    final?: number;
    assignments?: number[];
  };
}

interface Class {
  id: string;
  name: string;
  course: string;
  studentCount: number;
  teacher: string;
  startDate: string;
  status: "active" | "finished";
  description?: string;
  schedule?: {
    weekday: number;
    startTime: string;
    endTime: string;
    location: string;
  };
}

interface FormValues extends Omit<Class, "id" | "studentCount"> {}
interface StudentFormValues extends Omit<Student, "id"> {}

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const StatusTag = styled(Tag)<{ $status: Class["status"] }>`
  &.ant-tag-green {
    background-color: #f6ffed;
  }
  &.ant-tag-default {
    background-color: #f5f5f5;
  }
`;

const PerformanceTag = styled(Tag)<{ $performance: Student["performance"] }>`
  &.ant-tag-success {
    background-color: #f6ffed;
  }
  &.ant-tag-processing {
    background-color: #e6f7ff;
  }
  &.ant-tag-warning {
    background-color: #fff7e6;
  }
  &.ant-tag-error {
    background-color: #fff1f0;
  }
`;

const ClassManagement: React.FC = () => {
  // 状态管理
  const [activeTab, setActiveTab] = useState<string>("1");
  const [classes, setClasses] = useState<Class[]>([
    {
      id: "1",
      name: "嵌入式2301班",
      course: "嵌入式系统开发",
      studentCount: 35,
      teacher: "张老师",
      startDate: "2024-03-01",
      status: "active",
      schedule: {
        weekday: 1,
        startTime: "08:00",
        endTime: "09:40",
        location: "教学楼B-201",
      },
    },
    {
      id: "2",
      name: "物联网2302班",
      course: "物联网技术",
      studentCount: 40,
      teacher: "张老师",
      startDate: "2024-03-15",
      status: "active",
      schedule: {
        weekday: 3,
        startTime: "10:00",
        endTime: "11:40",
        location: "教学楼A-305",
      },
    },
  ]);

  const [students, setStudents] = useState<Student[]>([
    {
      id: "1",
      name: "李明",
      studentId: "2024001",
      gender: "男",
      phone: "13800138000",
      email: "liming@example.com",
      group: "A组",
      performance: "good",
      attendance: 95,
      scores: {
        midterm: 85,
        final: 88,
        assignments: [90, 85, 92],
      },
    },
    {
      id: "2",
      name: "王芳",
      studentId: "2024002",
      gender: "女",
      phone: "13800138001",
      email: "wangfang@example.com",
      group: "B组",
      performance: "excellent",
      attendance: 98,
      scores: {
        midterm: 92,
        final: 95,
        assignments: [95, 88, 96],
      },
    },
  ]);

  const [selectedClass, setSelectedClass] = useState<string | null>(null);
  const [selectedStudent, setSelectedStudent] = useState<string | null>(null);
  const [isClassModalVisible, setIsClassModalVisible] = useState(false);
  const [isStudentModalVisible, setIsStudentModalVisible] = useState(false);
  const [isScoreModalVisible, setIsScoreModalVisible] = useState(false);
  const [isAttendanceModalVisible, setIsAttendanceModalVisible] =
    useState(false);
  const [classForm] = Form.useForm<FormValues>();
  const [studentForm] = Form.useForm<StudentFormValues>();
  const [scoreForm] = Form.useForm();
  const [attendanceForm] = Form.useForm();

  const showModal = () => {
    setIsClassModalVisible(true);
  };

  const showStudentModal = () => {
    setIsStudentModalVisible(true);
  };

  const handleOk = async () => {
    try {
      const values = await classForm.validateFields();
      console.log("Form values:", values);
      message.success("班级创建成功！");
      setIsClassModalVisible(false);
      classForm.resetFields();
    } catch (error) {
      console.error("Validation failed:", error);
    }
  };

  const handleStudentOk = async () => {
    try {
      const values = await studentForm.validateFields();
      console.log("Student form values:", values);
      message.success("学生信息添加成功！");
      setIsStudentModalVisible(false);
      studentForm.resetFields();
    } catch (error) {
      console.error("Validation failed:", error);
    }
  };

  const handleCancel = () => {
    setIsClassModalVisible(false);
    classForm.resetFields();
  };

  const handleStudentCancel = () => {
    setIsStudentModalVisible(false);
    studentForm.resetFields();
  };

  // 文件上传配置
  const uploadProps: UploadProps = {
    name: "file",
    action: "/api/upload",
    headers: {
      authorization: "authorization-text",
    },
    accept: ".xlsx,.xls",
    showUploadList: false,
    beforeUpload: (file) => {
      const isExcel =
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
        file.type === "application/vnd.ms-excel";
      if (!isExcel) {
        message.error("只支持 Excel 文件！");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error("文件大小不能超过 2MB！");
        return false;
      }
      return true;
    },
    onChange: (info) => {
      if (info.file.status === "done") {
        message.success(`${info.file.name} 导入成功`);
        // 这里应该处理导入的数据
        // 模拟导入成功后更新数据
        if (activeTab === "1") {
          const newClasses: Class[] = [
            {
              id: Date.now().toString(),
              name: "导入班级示例",
              course: "示例课程",
              studentCount: 30,
              teacher: "张老师",
              startDate: new Date().toISOString().split("T")[0],
              status: "active",
            },
            // ... 更多导入的班级数据
          ];
          setClasses((prev) => [...prev, ...newClasses]);
        } else {
          const newStudents: Student[] = [
            {
              id: Date.now().toString(),
              name: "导入学生示例",
              studentId: "2024999",
              gender: "男",
              phone: "13800138999",
              email: "example@test.com",
              group: "C组",
              performance: "good",
            },
            // ... 更多导入的学生数据
          ];
          setStudents((prev) => [...prev, ...newStudents]);
        }
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 导入失败`);
      }
    },
  };

  // 导出功能
  const handleExport = (type: "class" | "student") => {
    message.loading({ content: "正在导出...", key: "export" });

    // 模拟导出过程
    setTimeout(() => {
      try {
        // 这里应该调用实际的导出 API
        const data = type === "class" ? classes : students;
        const fileName = type === "class" ? "班级名单.xlsx" : "学生名单.xlsx";

        // 创建一个临时的 a 标签来触发下载
        const link = document.createElement("a");
        link.href = `/api/export/${type}`;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        message.success({ content: "导出成功！", key: "export" });
      } catch (error) {
        message.error({ content: "导出失败，请重试", key: "export" });
      }
    }, 1500);
  };

  // 处理成绩编辑
  const handleScoreEdit = (student: Student) => {
    setSelectedStudent(student.id);
    scoreForm.setFieldsValue({
      midterm: student.scores?.midterm,
      final: student.scores?.final,
      assignments: student.scores?.assignments,
    });
    setIsScoreModalVisible(true);
  };

  // 处理考勤编辑
  const handleAttendanceEdit = (student: Student) => {
    setSelectedStudent(student.id);
    attendanceForm.setFieldsValue({
      attendance: student.attendance,
    });
    setIsAttendanceModalVisible(true);
  };

  // 保存成绩
  const handleScoreSave = async () => {
    try {
      const values = await scoreForm.validateFields();
      setStudents((prev) =>
        prev.map((student) =>
          student.id === selectedStudent
            ? {
                ...student,
                scores: values,
                // 根据成绩自动计算表现等级
                performance: calculatePerformance(values),
              }
            : student
        )
      );
      message.success("成绩保存成功");
      setIsScoreModalVisible(false);
      scoreForm.resetFields();
    } catch (error) {
      console.error("Save score failed:", error);
    }
  };

  // 保存考勤
  const handleAttendanceSave = async () => {
    try {
      const values = await attendanceForm.validateFields();
      setStudents((prev) =>
        prev.map((student) =>
          student.id === selectedStudent
            ? {
                ...student,
                attendance: values.attendance,
              }
            : student
        )
      );
      message.success("考勤保存成功");
      setIsAttendanceModalVisible(false);
      attendanceForm.resetFields();
    } catch (error) {
      console.error("Save attendance failed:", error);
    }
  };

  // 计算表现等级
  const calculatePerformance = (
    scores: Student["scores"]
  ): Student["performance"] => {
    if (!scores) return "normal";

    const midterm = scores.midterm || 0;
    const final = scores.final || 0;
    const assignments = scores.assignments || [];
    const avgAssignment = assignments.length
      ? assignments.reduce((a, b) => a + b, 0) / assignments.length
      : 0;

    const totalScore = midterm * 0.3 + final * 0.5 + avgAssignment * 0.2;

    if (totalScore >= 90) return "excellent";
    if (totalScore >= 80) return "good";
    if (totalScore >= 60) return "normal";
    return "poor";
  };

  const classColumns = [
    {
      title: "班级名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "课程",
      dataIndex: "course",
      key: "course",
    },
    {
      title: "学生人数",
      dataIndex: "studentCount",
      key: "studentCount",
    },
    {
      title: "班主任",
      dataIndex: "teacher",
      key: "teacher",
    },
    {
      title: "开课时间",
      dataIndex: "startDate",
      key: "startDate",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => (
        <Tag color={status === "active" ? "green" : "default"}>
          {status === "active" ? "进行中" : "已结束"}
        </Tag>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (text: string, record: Class) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setSelectedClass(record.id);
              classForm.setFieldsValue(record);
              setIsClassModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => {
              Modal.confirm({
                title: "确认删除",
                content: `确定要删除${record.name}吗？`,
                onOk() {
                  message.success("删除成功");
                },
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const studentColumns = [
    {
      title: "学号",
      dataIndex: "studentId",
      key: "studentId",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "性别",
      dataIndex: "gender",
      key: "gender",
    },
    {
      title: "联系电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "分组",
      dataIndex: "group",
      key: "group",
      render: (group: string) => <Tag color="blue">{group}</Tag>,
    },
    {
      title: "表现",
      dataIndex: "performance",
      key: "performance",
      render: (performance: string) => {
        const colors = {
          excellent: "green",
          good: "blue",
          normal: "orange",
          poor: "red",
        };
        const texts = {
          excellent: "优秀",
          good: "良好",
          normal: "一般",
          poor: "需要改进",
        };
        return (
          <Tag color={colors[performance as keyof typeof colors]}>
            {texts[performance as keyof typeof texts]}
          </Tag>
        );
      },
    },
    {
      title: "考勤率",
      dataIndex: "attendance",
      key: "attendance",
      render: (attendance: number) => (
        <Tooltip title={`${attendance}%`}>
          <Progress
            percent={attendance}
            size="small"
            status={attendance < 80 ? "exception" : "normal"}
          />
        </Tooltip>
      ),
    },
    {
      title: "成绩",
      key: "scores",
      render: (_: any, record: Student) => (
        <Space>
          {record.scores?.midterm && (
            <Tooltip title="期中成绩">
              <Tag color="blue">{record.scores.midterm}</Tag>
            </Tooltip>
          )}
          {record.scores?.final && (
            <Tooltip title="期末成绩">
              <Tag color="green">{record.scores.final}</Tag>
            </Tooltip>
          )}
          {record.scores?.assignments && (
            <Tooltip title="平均作业成绩">
              <Tag color="orange">
                {(
                  record.scores.assignments.reduce((a, b) => a + b, 0) /
                  record.scores.assignments.length
                ).toFixed(1)}
              </Tag>
            </Tooltip>
          )}
        </Space>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: Student) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleScoreEdit(record)}>
            编辑成绩
          </Button>
          <Button type="link" onClick={() => handleAttendanceEdit(record)}>
            登记考勤
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setSelectedStudent(record.id);
              studentForm.setFieldsValue(record);
              setIsStudentModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => {
              Modal.confirm({
                title: "确认删除",
                content: `确定要删除学生${record.name}的信息吗？`,
                onOk() {
                  message.success("删除成功");
                },
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const items: TabsProps["items"] = [
    {
      key: "1",
      label: (
        <span>
          <TeamOutlined />
          班级管理
        </span>
      ),
      children: (
        <StyledCard
          title="班级列表"
          extra={
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setIsClassModalVisible(true)}
              >
                新建班级
              </Button>
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>导入班级</Button>
              </Upload>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport("class")}
              >
                导出班级
              </Button>
            </Space>
          }
        >
          <Table columns={classColumns} dataSource={classes} rowKey="id" />
        </StyledCard>
      ),
    },
    {
      key: "2",
      label: (
        <span>
          <UserOutlined />
          学生管理
        </span>
      ),
      children: (
        <StyledCard
          title="学生列表"
          extra={
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setIsStudentModalVisible(true)}
              >
                添加学生
              </Button>
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>批量导入</Button>
              </Upload>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport("student")}
              >
                导出名单
              </Button>
            </Space>
          }
        >
          <Table columns={studentColumns} dataSource={students} rowKey="id" />
        </StyledCard>
      ),
    },
  ];

  return (
    <div>
      <Tabs
        defaultActiveKey="1"
        items={items}
        onChange={(key) => setActiveTab(key)}
      />

      {/* 班级模态框 */}
      <Modal
        title={selectedClass ? "编辑班级" : "新建班级"}
        open={isClassModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={600}
      >
        <Form
          form={classForm}
          layout="vertical"
          initialValues={{ status: "active" }}
        >
          <Form.Item
            name="name"
            label="班级名称"
            rules={[{ required: true, message: "请输入班级名称" }]}
          >
            <Input placeholder="请输入班级名称" />
          </Form.Item>
          <Form.Item
            name="course"
            label="课程"
            rules={[{ required: true, message: "请选择课程" }]}
          >
            <Select placeholder="请选择课程">
              <Option value="嵌入式系统开发">嵌入式系统开发</Option>
              <Option value="物联网技术">物联网技术</Option>
              <Option value="单片机原理">单片机原理</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="startDate"
            label="开课时间"
            rules={[{ required: true, message: "请选择开课时间" }]}
          >
            <Input type="date" />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select>
              <Option value="active">进行中</Option>
              <Option value="finished">已结束</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 学生模态框 */}
      <Modal
        title="添加/编辑学生"
        open={isStudentModalVisible}
        onOk={handleStudentOk}
        onCancel={handleStudentCancel}
        width={600}
      >
        <Form form={studentForm} layout="vertical">
          <Form.Item
            name="studentId"
            label="学号"
            rules={[{ required: true, message: "请输入学号" }]}
          >
            <Input placeholder="请输入学号" />
          </Form.Item>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            name="gender"
            label="性别"
            rules={[{ required: true, message: "请选择性别" }]}
          >
            <Select placeholder="请选择性别">
              <Option value="男">男</Option>
              <Option value="女">女</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="phone"
            label="联系电话"
            rules={[{ required: true, message: "请输入联系电话" }]}
          >
            <Input placeholder="请输入联系电话" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item name="group" label="分组">
            <Select placeholder="请选择分组">
              <Option value="A组">A组</Option>
              <Option value="B组">B组</Option>
              <Option value="C组">C组</Option>
            </Select>
          </Form.Item>
          <Form.Item name="performance" label="表现">
            <Select placeholder="请评价学生表现">
              <Option value="excellent">优秀</Option>
              <Option value="good">良好</Option>
              <Option value="normal">一般</Option>
              <Option value="poor">需要改进</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 成绩编辑模态框 */}
      <Modal
        title="编辑成绩"
        open={isScoreModalVisible}
        onOk={handleScoreSave}
        onCancel={() => {
          setIsScoreModalVisible(false);
          scoreForm.resetFields();
        }}
      >
        <Form form={scoreForm} layout="vertical">
          <Form.Item
            name="midterm"
            label="期中成绩"
            rules={[{ type: "number", min: 0, max: 100 }]}
          >
            <InputNumber min={0} max={100} />
          </Form.Item>
          <Form.Item
            name="final"
            label="期末成绩"
            rules={[{ type: "number", min: 0, max: 100 }]}
          >
            <InputNumber min={0} max={100} />
          </Form.Item>
          <Form.List name="assignments">
            {(fields, { add, remove }) => (
              <>
                {fields.map((field, index) => (
                  <Form.Item
                    label={`作业${index + 1}`}
                    required={false}
                    key={field.key}
                  >
                    <Form.Item
                      {...field}
                      validateTrigger={["onChange", "onBlur"]}
                      rules={[
                        {
                          required: true,
                          whitespace: true,
                          type: "number",
                          min: 0,
                          max: 100,
                          message: "请输入0-100的分数",
                        },
                      ]}
                      noStyle
                    >
                      <InputNumber min={0} max={100} />
                    </Form.Item>
                    {fields.length > 1 && (
                      <Button
                        type="link"
                        onClick={() => remove(field.name)}
                        style={{ marginLeft: 8 }}
                      >
                        删除
                      </Button>
                    )}
                  </Form.Item>
                ))}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    icon={<PlusOutlined />}
                  >
                    添加作业成绩
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>

      {/* 考勤编辑模态框 */}
      <Modal
        title="登记考勤"
        open={isAttendanceModalVisible}
        onOk={handleAttendanceSave}
        onCancel={() => {
          setIsAttendanceModalVisible(false);
          attendanceForm.resetFields();
        }}
      >
        <Form form={attendanceForm} layout="vertical">
          <Form.Item
            name="attendance"
            label="出勤率"
            rules={[{ required: true, type: "number", min: 0, max: 100 }]}
          >
            <InputNumber<number>
              min={0}
              max={100}
              formatter={(value) => `${value}%`}
              parser={(value) => {
                const parsed = value ? parseInt(value.replace("%", "")) : 0;
                return Math.min(Math.max(parsed, 0), 100);
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ClassManagement;
